package model.location;

import com.google.zxing.ResultPoint;

public class ReferencePoint {

	private String _decodedValue;
	
	private int _x;
	private int _y;
	
	private WorldCoordinate _coord;
	
	private ResultPoint[] resultPoints;
	
	private int[] bounds;
	
	public ReferencePoint(String decodedValue, int x, int y, ResultPoint[] resultPoints)
	{
		init(decodedValue, x, y);
		
		this.resultPoints = resultPoints;
		decodedValueToCoord();
	}
	
	public ReferencePoint(String decodedValue, int x, int y, int[] bounds)
	{
		init(decodedValue, x, y);
		
		this.bounds = bounds;
		decodedValueToCoord();
	}
	
	private void init(String decodedValue, int x, int y)
	{
		_decodedValue = decodedValue;
		_x = x;
		_y = y;
		_coord = new WorldCoordinate();
		
		decodedValueToCoord();
	}
	
	public String getDecodedValue()
	{
		return _decodedValue;
	}

	public int getX()
	{
		return _x;
	}
	
	public int getY()
	{
		return _y;
	}
	
	public float[] getPoints()
	{
		if(resultPoints != null)
			return getResultPoints();
		if(bounds != null)
			return getBounds();
		
		return new float[0];
	}
	
	private float[] getResultPoints()
	{
		//resultpoint has X & Y values
		float[] points = new float[resultPoints.length * 2];
		
		int j = 0;
		for (int i = 0; i < resultPoints.length; i++) 
		{
			points[j++] = resultPoints[i].getX();
			points[j++] = resultPoints[i].getY();
		}
		return points;
	}
	
	private float[] getBounds()
	{
		float[] points = new float[4];
		
		points[0] = (float) bounds[0];
		points[1] = (float) bounds[1];
		points[2] = (float) (bounds[0] + bounds[2]);
		points[3] = (float) (bounds[1] + bounds[3]);
		
		return points;
	}
	
	public WorldCoordinate getCoordinate()
	{
		if(!_coord.hasBeenInitialized())
			decodedValueToCoord();
		return _coord;
	}
	
	private void decodedValueToCoord()
	{
		String[] values = _decodedValue.split("_");
		_coord = new WorldCoordinate(Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2]));
	}
	
	public int getHeight()
	{
		if(resultPoints != null)
			return (int) (resultPoints[0].getY() - resultPoints[1].getY());
		if(bounds != null && bounds.length >= 4)
		{
			float[] points = getPoints();
			return (int) points[3] - (int) points[1];
		}
						
		return 0;
	}
}
